package controller;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;

/**
 * @author HLF
 * @version V1.0
 * @package controller
 * @date 2021/11/3 11:37
 */
public class UploadImg extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        Connection conn = null;
        Integer id = 0;
        String name = null;
        try {
            //1.判断当前上传的数据格式是否是多段的格式。
            if (ServletFileUpload.isMultipartContent(req)) {
                //创建FileItemFactory工厂实现类
                FileItemFactory fileItemFactory = new DiskFileItemFactory();
                //创建用于解析和上传数据的工具类ServletFileUpload
                ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
                try {
                    //2.解析上传的数据,得到每一个表单项FileItem
                    List<FileItem> list = servletFileUpload.parseRequest(req);
                    //3.循环判断每一个表单项，是普通表单项还是上传文件表单项
                    for (FileItem fileItem : list) {
                        if (fileItem.isFormField()) {//普通表单项
                            if ("id".equals(fileItem.getFieldName())) {
                                id = Integer.valueOf(fileItem.getString("UTF-8"));
                            } else if ("name".equals(fileItem.getFieldName())) {
                                name = fileItem.getString("UTF-8");
                            }
                        } else {//上传文件表单项
                            //4.将上传的文件写入磁盘(用用户id（主键唯一）命名头像)
                            fileItem.write(new File("D:\\JavaWeb\\HfsSale\\src\\main\\webapp\\imgs\\userUpload\\"
                                    + id + ".jpg"));
                        }
                    }
                    //5.执行插入语句
                    conn = JDBCUtils.getDruidConnection();
                    String sql = "insert into test values(?,?);";
                    QueryRunner runner = new QueryRunner();
                    int update = runner.update(conn, sql, id, name);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } finally {
            JDBCUtils.closeResource(conn, null);
        }
    }
}
